<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );

include_once("./SendTemplateSMS.php");


/**
 * 用户登录/退出控制器
 *
 * @category Controllers
 * @author 　二　阳°(QQ:707069100)
 * @link http://weibo.com/513778937?topnav=1&wvr=5
 */
class App extends MY_Controller {

	
	/**
	 * 构造函数
	 *
	 * @access public
	 * @return void
	 */
	function __construct() {
		parent::__construct ();

		session_start();
		if ("/".strpos($this->uri->uri_string, "app/desc") ){
            // header("Content-type: text/html");
		}
        else if (!isset($_SESSION['id']) && $this->uri->uri_string!="app/login") {
            header("Content-type: application/json");
            echo json_encode(array("code"=>1,"result"=>"未登录"));
            die();
        }
	}
	
	function login() {
		// 判断是否已经登录

	    // 用户名
		$username = strtolower($this->input->post ( 'username' ));
		// 密码
		$password = $this->input->post ( 'password' );

		$lang = $this->input->post('lang');

		if ($lang == null || $lang == "") {
		 	$lang = "en";
		 } 
		// 检查用户和密码
		$login = $this->login_manager ( $username, $password, false );
		if ($login) {
			// $this->session->set_flashdata ( 'lang', 'en' );
			$_SESSION["lang"] = $lang;
			$login["session_id"] = session_id();

			if ($login["role_id"]==3) {
				$login["role_name_cn"] = "业主";
				$login["role_name_en"] = "Owner";
			}
			if ($login["role_id"]==4) {
				$login["role_name_cn"] = "客户";
				$login["role_name_en"] = "Customer";
			}
			if ($login["role_id"]==5) {
				$login["role_name_cn"] = "工程师";
				$login["role_name_en"] = "Engineer";
			}
			if ($login["role_id"]==6) {
				$login["role_name_cn"] = "工程师主管";
				$login["role_name_en"] = "Director";
			}
			
			$this->echoApp($login);
		} else {
			$this->echoApp('error',1);			
		}
	}

	function changeLang($lang){
		$_SESSION["lang"] = $lang;
		$this->echoApp("success");
	}

	function caseList(){
		$start = $this->input->get ( 'start' );
		if ($start == null) {
			$start = 0;
		}
		$this->db->select ( "path,id,title_".$_SESSION["lang"]." as name,introduce_".$_SESSION["lang"]." as introduce" );
		$this->db->order_by ( "id","desc" );
		$this->db->limit ( 10,$start );
		$result = $this->db->get ( 'success' );
		$result = $result->result_array ();
		$this->echoApp($result);
	}

	function caseFirstList(){
		$start = $this->input->get ( 'start' );
		if ($start == null) {
			$start = 0;
		}
		$this->db->select ( "path,id,title_".$_SESSION["lang"]." as name,introduce_".$_SESSION["lang"]." as introduce" );
		
		$this->db->limit ( 4,$start );
		$this->db->order_by ( "id","desc" );
		$result = $this->db->get ( 'success' );
		$result = $result->result_array ();
		$this->echoApp($result);
	}

	function menulist($pid=0){

		$productId = $this->input->post ( 'productId' );
		if ($productId == null ){
                $productId = $this->input->post ( 'product_id' );
		}
		if ($_SESSION["role_id"] != 6) {
			$this->db->select ( "id" );
			$this->db->where("product_id",$productId);
			$this->db->where("user_id",$_SESSION["id"]);
			$result = $this->db->get ( 'product_user' );
			$result = $result->row_array ();
			if (count($result)==0) {
				$this->echoApp(array());
				die();
			}
		}

		$this->db->select ( "id,name_".$_SESSION["lang"]." as name,name_cn,name_en" );
		$this->db->where("pid",$pid);
		$result = $this->db->get ( 'menu' );
		$result = $result->result_array ();


		$this->db->select ( "id,menu_id" );
		$this->db->where("user_id",$_SESSION["id"]);
		$unmenu = $this->db->get ( 'menu_user' );
		$unmenu = $unmenu->result_array ();

		$res = array();

		foreach ($result as $key => $item) {
			$flag = true;
			foreach ($unmenu as $key1 => $value) {
				if ($value["menu_id"] == $item["id"]) {
					$flag = false;
				}
			}
			if ($flag) {
				array_push($res, $item);
			}
		}

		foreach ($res as $key => &$value) {
			$value["isfile"] = 0;
			$value["name_en"] =  preg_replace('# #', '', strtolower($value["name_en"]));
			$value["name_en"] =  preg_replace('#&#', '', strtolower($value["name_en"]));
		}

		

		$this->db->select ( "id,name,path" );
		$this->db->where("mid",$pid);
		$this->db->where("pid",$productId);
		$files = $this->db->get ( 'product_file' );
		$files = $files->result_array ();

		foreach ($files as $key => &$value) {
			$value["isfile"] = 1;
		}

		$this->echoApp(array_merge($res,$files));
	}

	function login_manager($username, $password) {
		$this->load->helper ( 'my_md5' );
		$this->db->select ( '*' );
		$this->db->where ( 'username', $username );
		$this->db->where ( 'password', str_md5 ( $password ) );
		$this->db->limit ( 1 );
		$result = $this->db->get ( 'manager' );
		$result = $result->row_array ();
		
		if (sizeof ( $result ) > 0) {
			$manager = array ();
			$manager ['manager'] = array ();
			$manager ['manager'] ['id'] = $result ['id'];
			$manager ['manager'] ['username'] = $result ['username'];
			$manager ['manager'] ['role_id'] = $result ['role_id'];
			$manager ['manager'] ['status'] = $result ['status'];
			$_SESSION = $result;
			return $result;
		} else {
			return false;
		}
	}

	function forgetPassword(){
		$phone = $this->input->get ( 'phone' );

		$this->db->select ( "password_origin" );
		$this->db->where("phone",$phone);
		$result = $this->db->get ( 'manager' );
		$result = $result->row_array ();

		if (!isset($result["password_origin"])) {
			$this->echoApp("没有该手机号");
			return;
		}
		sendTemplateSMS($phone ,array($result["password_origin"],'5'),"112831");//手机号码，替换内容数组，模板ID
		// $result["password_origin"]
		$this->echoApp("已经将密码发送到手机");
	}

	function getFilterList(){
		$this->db->select ( "id,name_".$_SESSION["lang"]." as name" );
		$result = $this->db->get ( 'product_progress' );
		$result = $result->result_array ();
		$this->echoApp($result);
	}


// http://localhost/admin/app/getMyProduct?filter=1,2,3
	// 这样传这个参数，不传filter代表全部，传的话传progressid
	function getMyProduct(){
		$filter = $this->input->get("filter");

		if ($_SESSION["role_id"] == 6) {
			if ($filter) {
				$result = $this->db->query("SELECT 
				    b.id as id,b.name_".$_SESSION["lang"]." as name,c.name_".$_SESSION["lang"]." as progress,num,update_time FROM
				    cn_product b
				        inner JOIN
				    cn_product_progress c ON b.progress = c.id where c.id in (".$filter.") order by update_time desc;")->result_array ();	
			}else{
				$result = $this->db->query("SELECT 
				    b.id as id,b.name_".$_SESSION["lang"]." as name,c.name_".$_SESSION["lang"]." as progress,num,update_time FROM
				    cn_product b
				        inner JOIN
				    cn_product_progress c ON b.progress = c.id order by update_time desc;")->result_array ();
			}
		} else {
			if ($filter) {
				$result = $this->db->query("SELECT 
				    b.id as id,b.name_".$_SESSION["lang"]." as name,c.name_".$_SESSION["lang"]." as progress,num,update_time FROM
				    cn_product b
				        inner JOIN
				    cn_product_user a on b.id = a.product_id and a.user_id=".$_SESSION["id"]."
				     	inner join
				    cn_product_progress c ON b.progress = c.id where c.id in (".$filter.") order by update_time desc;")->result_array ();	
			}else{
				$result = $this->db->query("SELECT 
				    b.id as id,b.name_".$_SESSION["lang"]." as name,c.name_".$_SESSION["lang"]." as progress,num,update_time FROM
				    cn_product b
				        inner JOIN
				    cn_product_user a on b.id = a.product_id and a.user_id=".$_SESSION["id"]."
				        inner JOIN
				    cn_product_progress c ON b.progress = c.id order by update_time desc;")->result_array ();
			}
		}

		
		

		foreach ($result as $key => &$value) {
			$value["update_time"] = date('Y-m-d H:i', $value["update_time"]);
		}

		$this->echoApp($result);
	}

	function addMedia(){
		$productId = $this->input->post ( 'product_id' );

		if ($_SESSION["role_id"] != 6) {
			$this->db->select ( "id" );
			$this->db->where("product_id",$productId);
			$this->db->where("user_id",$_SESSION["id"]);
			$result = $this->db->get ( 'product_user' );
			$result = $result->row_array ();
			if (count($result)==0) {
				$this->echoApp(array());
				die();
			}
		}

		$db_table = $this->db->dbprefix ( 'product_media' );
		$pid = $this->input->post ( 'product_id' );
		$name = $this->input->post ( 'name' );
		$path = $this->input->post ( 'path' );
		if ($path == null) {
			$path = $this->input->post ( 'mediaPath' );
		}
		$imgpath = $this->input->post ( 'imgpath' );
		$type = $this->input->post ( 'type' );
		$this->db->insert ( $db_table, array("userid"=>$_SESSION["id"],
			"pid"=>$pid,
			"name"=>$name,
			"imgpath"=>$imgpath,
			"path"=>$path,
			"type"=>$type,
			"create_time"=>time()
			) );

		$this->echoApp($this->db->insert_id ());
	}

	function getMedia($pid){
		if ($_SESSION["role_id"] != 6) {
			$this->db->select ( "id" );
			$this->db->where("product_id",$pid);
			$this->db->where("user_id",$_SESSION["id"]);
			$result = $this->db->get ( 'product_user' );
			$result = $result->row_array ();
			if (count($result)==0) {
				$this->echoApp(array());
				die();
			}
		}

		$start = $this->input->get ( 'start' );
		if ($start == null) {
			$start = 0;
		}
		$result = $this->db->query("SELECT 
		    b.id as id,b.name as introduce,b.imgpath,b.userid,r.id as roleid, b.path,b.type,c.nickname as nickname,r.name as rolename,create_time FROM
		    cn_product_media b
		        inner JOIN
		    cn_manager c ON b.userid = c.id
		    	inner join
		    cn_role r on r.id=c.role_id where b.pid=".$pid."  order by id desc limit ".$start.",10;")->result_array ();
		
		foreach ($result as $key => &$value) {
			if ($_SESSION["lang"] == "en"){
				if ($value["roleid"]==3) {
					$value["rolename"] = "Owner";
				}
				if ($value["roleid"]==4) {
					$value["rolename"] = "Customer";
				}
				if ($value["roleid"]==5) {
					$value["rolename"] = "Engineer";
				}
				if ($value["roleid"]==6) {
					$value["rolename"] = "Director";
				}
			}
			$value["create_time"] = date('Y-m-d H:i', $value["create_time"]);
		}

		$this->echoApp($result);
	}

	function deleteMedia($id){
		
		$db_table = $this->db->dbprefix ( 'product_media' );
		$this->db->delete ( $db_table, array("id"=>$id) );

		$this->echoApp($this->db->affected_rows ());
	}

	function addComment(){

		$pid = $this->input->post ( 'product_id' );

		if ($_SESSION["role_id"] != 6) {
			$this->db->select ( "id" );
			$this->db->where("product_id",$pid);
			$this->db->where("user_id",$_SESSION["id"]);
			$result = $this->db->get ( 'product_user' );
			$result = $result->row_array ();
			if (count($result)==0) {
				$this->echoApp(array());
				die();
			}
		}

		$db_table = $this->db->dbprefix ( 'product_comment' );
		$content = $this->input->post ( 'content' );
		$this->db->insert ( $db_table, array("userid"=>$_SESSION["id"],
			"pid"=>$pid,
			"content"=>$content,
			"create_time"=>time()
			) );

		$this->echoApp($this->db->insert_id ());
	}

	function getComment($pid){
		if ($_SESSION["role_id"] != 6) {
			$this->db->select ( "id" );
			$this->db->where("product_id",$pid);
			$this->db->where("user_id",$_SESSION["id"]);
			$result = $this->db->get ( 'product_user' );
			$result = $result->row_array ();
			if (count($result)==0) {
				$this->echoApp(array());
				die();
			}
		}

		$start = $this->input->get ( 'start' );
		if ($start == null) {
			$start = 0;
		}
		$result = $this->db->query("SELECT 
		    b.id as id,b.content as content,b.userid,r.id as roleid,c.nickname as nickname,r.name as rolename,create_time FROM
		    cn_product_comment b
		        inner JOIN
		    cn_manager c ON b.userid = c.id
		    	inner join
		    cn_role r on r.id=c.role_id where b.pid=".$pid."  order by id desc limit ".$start.",10;")->result_array ();
		
		foreach ($result as $key => &$value) {
			if ($_SESSION["lang"] == "en"){
				if ($value["roleid"]==3) {
					$value["rolename"] = "Owner";
				}
				if ($value["roleid"]==4) {
					$value["rolename"] = "Customer";
				}
				if ($value["roleid"]==5) {
					$value["rolename"] = "Engineer";
				}
				if ($value["roleid"]==6) {
					$value["rolename"] = "Director";
				}
			}

			$value["create_time"] = date('Y-m-d H:i', $value["create_time"]);
		}

		$this->echoApp($result);
	}

	function deleteComment($id){
		
		$db_table = $this->db->dbprefix ( 'product_comment' );
		$this->db->delete ( $db_table, array("id"=>$id) );

		$this->echoApp($this->db->affected_rows ());
	}

	function editPassword(){
		$this->load->helper ( 'my_md5' );

        $save ['password'] = $this->input->post ( 'password' );
        $db_table = $this->db->dbprefix ( 'manager' );
		$this->db->update ( $db_table, array('password' => str_md5 ( $save ['password'] ),
            'password_origin' => $save ['password']),array("id"=>$_SESSION["id"]) );

		$this->echoApp($this->db->affected_rows ());
	}

	function searchFile(){
        $file = $this->input->post ( 'file' );
        $result = $this->db->query("SELECT 
		    name,path from cn_product_file where name like '%".$file."%';")->result_array ();

		$this->echoApp($result);
	}

	function feedback(){
        $content = $this->input->post ( 'content' );
        $db_table = $this->db->dbprefix ( 'feedback' );
		$this->db->insert ( $db_table, array("userid"=>$_SESSION["id"],
			"content"=>$content,
			"create_time"=>time()
			) );

		$this->echoApp($this->db->insert_id ());
	}

	function echoApp($result,$code=0){
		header("Content-type: application/json");
    	echo json_encode(array("code"=>$code,"data"=>$result));
	}

	function deleteMenu(){
		$content = $this->input->post ( 'menu' );
		foreach ($content as $key => $value) {
			$db_table = $this->db->dbprefix ( 'menu_user' );
			$this->db->delete ( $db_table, array("user_id"=>$_SESSION["id"],
			"menu_id"=>$value
			));
		}

		$this->echoApp($this->db->insert_id ());
	}

	function addMenu(){
		$content = $this->input->post ( 'menu' );
		foreach ($content as $key => $value) {
			$db_table = $this->db->dbprefix ( 'menu_user' );
			$this->db->insert ( $db_table, array("user_id"=>$_SESSION["id"],
			"menu_id"=>$value
			) );
		}
        

		$this->echoApp($this->db->insert_id ());
	}

	function menuSettingList(){
		$this->db->select ( "id,name_".$_SESSION["lang"]." as name,pid" );
		$result = $this->db->get ( 'menu' );
		$result = $result->result_array ();

		$this->db->select ( "id,menu_id" );
		$this->db->where("user_id",$_SESSION["id"]);
		$files = $this->db->get ( 'menu_user' );
		$files = $files->result_array ();

		foreach ($result as $key => &$value) {
			$value["checked"] = 1;
		}

		foreach ($result as $key => &$value) {
			foreach ($files as $key => $item) {
				if ($value["id"] == $item["menu_id"]) {
					$value["checked"] = 0;
				}
			}
		}

		foreach ($files as $key => &$value) {
			$value["isfile"] = 1;
		}

		$this->echoApp($result);
	}

	function menuXFSettingList(){
		$this->db->select ( "id,name_".$_SESSION["lang"]." as name,pid" );
		$result = $this->db->get ( 'menu' );
		$result = $result->result_array ();

		$this->db->select ( "id,menu_id" );
		$this->db->where("user_id",$_SESSION["id"]);
		$files = $this->db->get ( 'menu_user' );
		$files = $files->result_array ();

		foreach ($result as $key => &$value) {
			$value["checked"] = 1;
		}

		foreach ($result as $key => &$value) {
			foreach ($files as $key => $item) {
				if ($value["id"] == $item["menu_id"]) {
					$value["checked"] = 0;
				}
			}
		}

		$tree =	classify_tree($result);
		$this->echoApp($tree);
	}

	function desc($id,$lang) {
		$this->db->select ("article_content_".$lang." as content");
		$this->db->where("id",$id);
		$result = $this->db->get ( 'article' );
		$result = $result->result_array ();
		header("Content-Type: text/html;charset=utf-8");
		echo "<style>img { height: auto; width: auto\9; width:100%; } </style>";
		echo $result[0]["content"];
	}
}

function classify_tree($datas, $requisite_field = array('id', 'pid')) {
	if (!$datas) {
		return array();
	}
	$new_datas = array();
	foreach ($datas as $v) {
		$new_datas[$v[$requisite_field[1]]][$v[$requisite_field[0]]] = $v;
	}
	return classify_tree_datas($new_datas, 0);
}

function classify_tree_datas($new_datas, $pid) {
	$CI = &get_instance();
	if (!isset($CI -> cate_list)) {
		$CI -> cate_list = array();
	}
	if (!isset($CI -> level)) {
		$CI -> level = 0;
	}
	foreach ($new_datas[$pid] as $k => $v) {
		$array_keys = array_keys($new_datas[$pid]);
		foreach ($array_keys as $n => $_k) {
			if ($_k == $k) {
				$next_key = isset($array_keys[$n + 1]) ? $array_keys[$n + 1] : '';
				break;
			}
		}
		if (!isset($new_datas[$pid][$next_key])) {
			$v['last_one'] = TRUE;
		}
		if (isset($new_datas[$k])) {
			$v['have_child'] = TRUE;
		}
		$v['level'] = $CI -> level;
		$CI -> cate_list[] = $v;
		if (isset($new_datas[$k])) {
			$CI -> level++;
			classify_tree_datas($new_datas, $k);
			$CI -> level--;
		}
	}
	return $CI -> cate_list;
}

/* End of file login.php */
/* Location: ./app/admin/controllers/login.php */
